const fs = require("fs");
const path = require("path");
const { getOptical } = require("../services/opticals.service");
const { DATA_PATH } = require("../config/config.default.js");
const readFile = async (ph, mode = 1) => {
  return new Promise((resolve, reject) => {
    var rs = "";
    try {
      fs.readFile(ph, "utf-8", (err, data) => {
        if (err) {
          if (mode == 1) {
            rs = JSON.parse("[]");
          } else {
            rs = JSON.parse("{}");
          }
          resolve(rs);
        } else {
          if (data === "") {
            if (mode == 1) {
              rs = JSON.parse("[]");
            } else {
              rs = JSON.parse("{}");
            }
          } else {
            rs = JSON.parse(data);
          }
          resolve(rs);
        }
      });
    } catch (error) {
      console.log(error);
      if (mode == 1) {
        rs = JSON.parse("[]");
      } else {
        rs = JSON.parse("{}");
      }
      resolve(rs);
    }
  });
};
const writeFile = async (ph, content) => {
  return new Promise((resolve, reject) => {
    try {
      fs.writeFile(ph, content, (err) => {
        if (err) {
          console.log(err);
          resolve(false);
        } else {
          resolve(true);
        }
      });
    } catch (error) {
      console.log(error);
      resolve(false);
    }
  });
};
const eraseFile = async (ph) => {
  return new Promise((resolve, reject) => {
    try {
      let rs = fs.unlinkSync(ph);
      resolve(true)
    } catch (error) {
      console.log(error);
      resolve(false)
    }

  })

}
//num为故障点距离
const getGaojing = (arr, num, longitude, latitude) => {
  try {
    let res = { code: -1, msg: "", data: {} };
    if (!(arr instanceof Array) || arr.length <= 1) {
      return { code: -1, msg: "节点太少，无法计算", data: "" };
    }
    if (Math.abs(latitude * 1) > 0 && Math.abs(longitude * 1) > 0) {
      //真实告警，带坐标
      if (arr.length < 2) {
        if (num == 0) {
          res.data.type = 2;
          res.data.origin = arr[0]['nodeName'];;
          res.data.finishing = arr[0]['nodeName'];
          res.data.originId = arr[0]['opticalId'];
          res.data.finishingId = arr[0]['opticalId'];
          res.data.distance = 0;
          res.data.x = 3836187.737 * (0 + arr[0]['longitude'] - 111.67240) / 0.86915612;
          res.data.y = -7091297.591 * (0 + arr[0]['latitude'] - 40.79964) / 1.20283173;
          res.data.R = arr[0]['R'];
          res.data.G = arr[0]['G'];
          res.data.B = arr[0]['B'];
          res.data.longitude = longitude;
          res.data.latitude = latitude;
          return res;
        } else {
          res.code = 1;
          res.msg = "超出范围"
          res.data = {}
          return res;
        }
      }
      //思路：假设两个点，A，B为节点坐标，C为故障点，判断C是否在AB这条直线上，方法为AC + BC 是否等AB，如果等于则在一条线上，否则不在一条线上。
      for (var i = 0; i < arr.length - 1; i++) {
        let x1 = 3836187.737 * (0 + arr[i]['longitude'] - 111.67240) / 0.86915612;
        let y1 = -7091297.591 * (0 + arr[i]['latitude'] - 40.79964) / 1.20283173;
        let x2 = 3836187.737 * (0 + arr[i + 1]['longitude'] - 111.67240) / 0.86915612;
        let y2 = -7091297.591 * (0 + arr[i + 1]['latitude'] - 40.79964) / 1.20283173;
        let x3 = 3836187.737 * (0 + longitude - 111.67240) / 0.86915612;
        let y3 = -7091297.591 * (0 + latitude - 40.79964) / 1.20283173;
        let ratio = (Math.abs(Math.sqrt(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2))) + Math.abs(Math.sqrt(Math.pow(x2 - x3, 2) + Math.pow(y2 - y3, 2)))) / Math.abs(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1,2)));
        if (ratio >= 0.995 && ratio <= 1.005) {
          res.code = 0;
          res.msg = "ok";
          res.data.type = 2;
          res.data.origin = arr[i]['nodeName'];
          res.data.finishing = arr[i + 1]['nodeName'];
          res.data.originId = arr[i]['opticalId'];
          res.data.finishingId = arr[i + 1]['opticalId'];
          res.data.x = x3;
          res.data.y = y3;
          let len = Math.abs(Math.sqrt(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2)));
          res.data.distance = Math.round((len * 1.8768 / 100) * 10) / 10;
          res.data.R = arr[i]['R'];
          res.data.G = arr[i]['G'];
          res.data.B = arr[i]['B'];
          res.data.longitude = longitude;
          res.data.latitude = latitude;
          return res;
        }
      }
      res.code = 1;
      res.msg = "超出范围",
        res.data = {};
      return res;
    } else {
      //模拟告警，不带坐标
      var sum = 0;
      var pre = 0;
      var distance = num * 100 / 1.8768;
      if (num == 0) {
        res.code = 0;
        res.msg = "ok";
        res.data.type = 2;
        res.data.origin = arr[0]['nodeName'];;
        res.data.finishing = arr[1]['nodeName'];
        res.data.originId = arr[0]['opticalId'];
        res.data.finishingId = arr[1]['opticalId'];
        res.data.distance = 0;
        res.data.x = 3836187.737 * (0 + arr[0]['longitude'] - 111.67240) / 0.86915612;
        res.data.y = -7091297.591 * (0 + arr[0]['latitude'] - 40.79964) / 1.20283173;
        res.data.R = arr[0]['R'];
        res.data.G = arr[0]['G'];
        res.data.B = arr[0]['B'];
        return res;
      }
      for (var i = 0; i < arr.length; i++) {
        pre = sum;
        //console.log(`i=>${i}---arr[i]=>${arr[i]}---arr.length=>${arr.length}`);
        if (i == arr.length - 1) {
          res.code = 1;
          res.msg = "故障点超出坐标点范围";
          res.data = ""
          return res;
        } else {
          let x1 = 3836187.737 * (0 + arr[i]['longitude'] - 111.67240) / 0.86915612;
          let y1 = -7091297.591 * (0 + arr[i]['latitude'] - 40.79964) / 1.20283173;
          let x2 = 3836187.737 * (0 + arr[i + 1]['longitude'] - 111.67240) / 0.86915612;
          let y2 = -7091297.591 * (0 + arr[i + 1]['latitude'] - 40.79964) / 1.20283173;
          let Len = Math.abs(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)));
          sum = sum + Len;
          if (distance <= sum) {
            res.code = 0;
            res.msg = "ok";
            res.data.type = 2;
            res.data.origin = arr[i]['nodeName'];
            res.data.finishing = arr[i + 1]['nodeName'];
            res.data.originId = arr[i]['opticalId'];
            res.data.finishingId = arr[i + 1]['opticalId'];
            let len = distance - pre;
            let n = len / Len;
            let x = x1 + n * (x2 - x1);
            let y = y1 + n * (y2 - y1);
            res.data.x = x;
            res.data.y = y;
            res.data.distance = Math.round((len * 1.8768 / 100) * 10) / 10;
            res.data.R = arr[i]['R'];
            res.data.G = arr[i]['G'];
            res.data.B = arr[i]['B'];
            return res;
          }
        }
      }
    }
  } catch (error) {
    console.log(error);
    return {code:-1,msg:"未知错误",data:error}
  }
}
const changeObj = (obj, key, value) => {
  obj[key] = value;
  return obj;
}
const updateJson = async (fileName) => {
  try {
    if (!fileName) {
      return { code: -1, msg: "文件不存在", data: fileName };
    }
    let obj = { sites: { UpData: "1" } };
    let rs = await writeFile(fileName, JSON.stringify(obj));
    setTimeout(async () => {
      obj.sites.UpData = "0";
      await writeFile(fileName, JSON.stringify(obj));
    }, 1000)
    return { code: 0, msg: "ok", data: obj };
  } catch (error) {
    console.log(error);
    return { code: -1, msg: error, data: "" };
  }
}

class POI {
  constructor(fileName) {
    this.fileName;
    this.json = {};
    this.arr = [];
  }
  async getJson() {
    let obj = await readFile(this.fileName, 2);
    if (!obj || !(obj instanceof Object) || Object.keys(obj).length == 0) {
      this.json = { sites: [] }
    }
  }
}

const changeColor = async (link, num, model = 1) => {
  try {
    if (!link || !(link instanceof Object) || Object.keys(link).length == 0) {
      return false;
    }
    if (num < 0) {
      return false
    }
    let start = 0;
    var opticals = await getOptical({ linkName: link.linkName });
    if (!opticals) {
      return false;
    }
    for (var j = 0; j < opticals.length; j++) {
      if (num == opticals[j]['opticalId']) {
        start = j;
      }
    }

    let jsonName = `${DATA_PATH}Js_Node${link.linkId}.json`;
    let nodes = await readFile(jsonName, 2);
    if (!nodes) {
      return false;
    }
    let json = nodes['sites'];
    if (!(json instanceof Array) || json.length == 0) {
      return false;
    }
    //model = 1为设置告警，R为0.2,否则r为原本颜色
    if (model == 1) {
      json[start]['R'] = "0.2";
      json[start]['G'] = "0";
      json[start]['B'] = "0";
      if (json[start + 1]) {
        json[start + 1]['R'] = "0.2";
        json[start + 1]['G'] = "0";
        json[start + 1]['B'] = "0";
      }
      if (json[start + 2]) {
        json[start + 2]['R'] = "0.2"
        json[start + 2]['G'] = "0"
        json[start + 2]['B'] = "0"
      }
    } else {
      for (var k = 0; k < json.length; k++) {
        json[k]['R'] = opticals[k]['R'];
        json[k]['G'] = opticals[k]['G'];
        json[k]['B'] = opticals[k]['B'];
      }
    }
    var res = await writeFile(jsonName, JSON.stringify({ sites: json, status: { Color: "" } }));
    if (!res) {
      return false;
    }
    //updateJson(`${DATA_PATH}Js_UpData.json`);
    return true;
  } catch (error) {
    console.log(error);
    return false;
  }
}

module.exports = {
  readFile,
  writeFile,
  eraseFile,
  getGaojing,
  updateJson,
  changeColor
};
